package com.company;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author $
 * @version 1.0
 * @date 2022年06月14日 12:25
 * @description: TODO
 */
public class GuessNumber extends JFrame{
    Integer answer;
    JTextField guessArea;
    Integer guess;
    JLabel title;
    JLabel prompt;
    JLabel hint;
    JButton guessBtn;
    JButton againBtn;
    Integer chances = 7;

    public void initGUI() {
        setTitle("猜数字游戏");
        setSize(500, 400);
        setLocation(400, 350);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(null);

        title = new JLabel("猜数字游戏");
        title.setBounds(180, 10, 100, 30);
        add(title);

        prompt = new JLabel("请输入一个1~100之间的数字");
        prompt.setBounds(70, 50, 180, 30);
        add(prompt);

        guessBtn = new JButton("猜一下");
        guessBtn.setBounds(160,90,100,30);
        GuessActionListener gal=new GuessActionListener();
        guessBtn.addActionListener(gal);
        add(guessBtn);
        againBtn =new JButton("再玩一次");
        againBtn.setBounds(160,125,100,30);
        AgainActionListener aal=new AgainActionListener();
        againBtn.addActionListener(aal);
        add(againBtn);
        guessArea = new JTextField();
        guessArea.setBounds(250, 50, 100, 30);
        add(guessArea);

        hint = new JLabel("欢迎来到猜数字游戏！点击一下开始游戏！");
        hint.setBounds(30, 165, 300, 30);
        add(hint);

        setVisible(true);


    }

    public void start() {
        answer = (int) (Math.random() * 100000) % 100;
        guessBtn.setVisible(true);
        guessArea.setVisible(true);
        againBtn.setVisible(false);
        hint.setText("欢迎来到猜数字游戏！点击开始游戏！");
    }

    public class GuessActionListener implements ActionListener{


        public void actionPerformed(ActionEvent e) {
            String message = "";
            if(chances>=1){
                chances = chances - 1;
                try{
                    guess = Integer.parseInt(guessArea.getText());
                    if(guess > answer){
                        message = "大了！还有"+chances+"机会";
                    }else if(guess < answer){
                        message = "小了！还有"+chances+"机会";
                    }else{
                        message = "猜对啦！";
                        guessBtn.setEnabled(false);
                        againBtn.setVisible(true);
                    }
                }catch (Exception exception){
                    message = "请输入正确的数字！还有"+chances+"机会";
                }
            }else{
                message = "没有机会啦！";
                guessBtn.setEnabled(false);
                againBtn.setVisible(true);
            }
            hint.setText(message);
        }

    }
}
